package com.jzl.util;

import org.springframework.util.StringUtils;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

public class CollectionUtil
{

    public static List<String> splitToList(String src, String regex)
    {
        if (StringUtils.isEmpty(src))
        {
            return Collections.emptyList();
        }
        String[] ss = src.split(regex);
        return Arrays.asList(ss);
    }

    public static <T> List<T> filterNull(List<T> list)
    {
        return list == null ? Collections.emptyList() : list
                .stream()
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
    }

    public static String joining(List<?> list, CharSequence delimiter)
    {
        list = filterNull(list);
        if (list == null || list.isEmpty())
        {
            return "";
        }
        return list.stream().map(Object::toString).collect(Collectors.joining(delimiter));
    }

    public static <T> String joining(List<T> list, Function<? super T, ? extends String> mapper, CharSequence delimiter)
    {
        list = filterNull(list);
        if (list == null || list.isEmpty())
        {
            return "";
        }
        return list.stream().map(mapper).collect(Collectors.joining(delimiter));
    }

    public static <K, T> Map<K, T> toMap(List<T> list, Function<T, K> keyFunction)
    {
        if (list == null || list.isEmpty())
        {
            return Collections.emptyMap();
        }

        return list.stream().collect(Collectors.toMap(keyFunction, t -> t));
    }

    public static <K, T> Map<K, List<T>> groupingBy(List<T> list, Function<T, K> keyFunction)
    {
        if (list == null || list.isEmpty())
        {
            return Collections.emptyMap();
        }

        return list.stream().collect(Collectors.groupingBy(keyFunction, Collectors.toList()));
    }

    public static <K, T, V> Map<K, V> toMap(List<T> list, Function<T, K> keyFunction, Function<T, V> valueFunction)
    {
        if (list == null || list.isEmpty())
        {
            return Collections.emptyMap();
        }
        return list.stream().collect(Collectors.toMap(keyFunction, valueFunction));
    }

    public static <T> List<List<T>> subList(List<T> src, int subSize)
    {
        if (src == null || src.isEmpty())
        {
            return Collections.emptyList();
        }

        int count = 0;
        List<List<T>> listList = new ArrayList<>();
        while (count < src.size())
        {
            int subCount = src.size() - count <= subSize ? src.size() - count : subSize;
            List<T> list = src.subList(count, subCount + count);
            if (!list.isEmpty())
            {
                listList.add(list);
                count += subCount;
            }
        }
        return listList;
    }

}
